package com.yao.securitydemo.filter;

import cn.hutool.core.util.StrUtil;
import com.yao.securitydemo.exception.VerificationCodeException;
import com.yao.securitydemo.handler.MyAuthenticationFailureHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @description:
 * @author: yaochenglong
 * @date: 2022/4/27 10:56
 */
public class VerificationCodeFilter extends OncePerRequestFilter {

    private MyAuthenticationFailureHandler handler = new MyAuthenticationFailureHandler();

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //非登录请求不校验验证码
        if(!"/test/login".equals(request.getRequestURI())){
            filterChain.doFilter(request,response);
        }else {
            try {
                verificationCode(request);

            } catch (VerificationCodeException e) {
                handler.onAuthenticationFailure(request,response,e);
                return;
            }
            filterChain.doFilter(request,response);
        }
    }

    private void verificationCode(HttpServletRequest request) throws VerificationCodeException {
        String requestCode = request.getParameter("captcha");
        String savedCode = (String) request.getSession().getAttribute("captcha");
        if (!StrUtil.isEmpty(savedCode)){
            request.getSession().removeAttribute("captcha");
        }

        //校验不通过抛出异常
        if (!savedCode.equals(requestCode)){
            throw new VerificationCodeException();
        }
    }
}
